<template>
  <div style="width:100%;height:auto; margin:0 auto;">
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px" label-position="left">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="模板类型" prop="type">
            <el-select v-model="form.type" style="width:100%;" clearable @change="selectGoodsByGroupId($event)">
              <template>
                <el-option v-for="item in xmTypes" :key="item.code" :label="item.name" :value="item.code" />
              </template>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="form.name" placeholder="模板名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="内容" prop="sortNum">
            <el-button type="primary" icon="el-icon-check" @click="txAdd">插入模板</el-button>
            <mavon-editor ref="md" v-model="content" style="height: 500px" @change="change" @imgAdd="imgAdd" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="text-align:center;">
      <el-button type="primary" @click="save('ruleForm')">确定</el-button>
      <el-button type="danger" @click="closePage">取消</el-button>
    </div>

    <el-dialog v-dialogDrag :close-on-click-modal="false" :visible.sync="xmAddVisible" append-to-body width="1200px" title="选择模板">
      <xm-add v-if="xmAddVisible" ref="xmAdd" :visible.sync="xmAddVisible" @sendmsg="getKhMsg" />
    </el-dialog>
  </div>
</template>

<script>
import { getInfo, edit } from '@/api/mdTemplate'
import { getDictListByCode } from '@/api/dict'
import { upload } from '@/api/projectFile'
import { Message } from 'element-ui'

import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

import XmAdd from '../../public/selectTemplate' // eslint-disable-line no-unused-vars

export default {
  inject: ['onLoadList'],
  components: { mavonEditor, XmAdd },
  props: { // 第二种方式
    proid: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {},
      rules: {
        type: [
          { required: true, message: '模板类型不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '模板名称不能为空', trigger: 'blur' }
        ]
      },
      content: '',
      html: '',
      xmAddVisible: false,
      xmTypes: []
    }
  },
  created() {
    this.getDictList('CDS_TEMPLATE_TYPE')
  },
  methods: {
    getDetailed() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getInfo({ code: this.proid }).then(response => {
        this.form = response.data
        this.content = response.data.markdownData

        loading.close()
      }).catch(function() {
        loading.close()
      })
    },
    getDictList(code) {
      getDictListByCode(code).then(response => {
        if (code === 'CDS_TEMPLATE_TYPE') {
          this.xmTypes = response.data
        }
      })
    },
    getDicName(code, flag) {
      if (flag === 'CDS_TEMPLATE_TYPE') {
        for (var i in this.xmTypes) {
          if (this.xmTypes[i].code === code) {
            return this.xmTypes[i].name
          }
        }
      }
    },
    txAdd() {
      this.xmAddVisible = true
      this.$nextTick(() => {
        this.$refs.xmAdd
      })
    },
    // 将图片上传到服务器，返回地址替换到md中
    imgAdd(pos, $file) {
      const formdata = new FormData()
      formdata.append('image', $file)
      // 访问后台服务器方法
      upload(formdata).then(res => {
        if (res.code === 20000) {
          this.$refs.md.$img2Url(pos, res.data.abstractPath)
        } else {
          this.$message.error(res.message)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 所有操作都会被解析重新渲染
    change(value, render) {
      this.form.htmlData = render
      this.form.markdownData = value
    },
    getKhMsg(data) {
      this.content = data.markdownData
    },
    save(ruleForm) { // 编辑
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          edit(this.form).then(response => {
            Message({
              message: '编辑成功',
              type: 'success',
              duration: 5 * 1000
            })

            this.$emit('update:visible', false)
            loading.close()
            this.onLoadList()
          }).catch(response => {
            loading.close()
            this.onLoadList()
          })
        }
      })
    },
    closePage() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>

</style>
